//
//  CarNoInputView.m
//  jieChe
//
//  Created by li on 16/8/3.
//  Copyright © 2016年 li. All rights reserved.
//

#import "CarNoInputView.h"
#import "KeyBoardView.h"
#import "PlateIDCameraViewController.h"

#define BTNTAG 200

@interface CarNoInputView ()
{
    NSMutableString *resultString;
}

@property (nonatomic,strong) KeyBoardView *keyBoardView;
@property (nonatomic,strong) UILabel *contentLabel;

@end

@implementation CarNoInputView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    _maxLength = _maxLength ?: 8;
    
    UILabel *tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, CGRectGetHeight(frame))];
    tipsLabel.text = @" 车牌:";
    
    CGFloat cameraBtnW = 30;
    CGFloat edge = 10;
    UIButton *cameraBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.width - cameraBtnW - edge, (self.height - cameraBtnW)/2.0, cameraBtnW, cameraBtnW)];
    [cameraBtn addTarget:self action:@selector(cameraBtn) forControlEvents:(UIControlEventTouchUpInside)];
    
    [cameraBtn setBackgroundImage:[UIImage imageNamed:@"扫一扫.png"] forState:(UIControlStateNormal)];
    
    [cameraBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    
    CGFloat btnW = (cameraBtn.x - tipsLabel.maxX)/8.0;
//    NSString *carfixString = ([[NSUserDefaults standardUserDefaults] objectForKey:CARFIX_KEY] ? : @"");
    NSString *carfixString = @"";
    resultString = [NSMutableString string];
    
    CGFloat lastX = tipsLabel.maxX;
    for (int i = 0; i < 8; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(lastX, (self.height - btnW)/2, btnW, btnW)];
        btn.layer.borderColor = kHexColor(0xc3c3c3).CGColor;
        btn.layer.borderWidth = 1;
        
        if (i == 7) {
            btn.backgroundColor = [UIColor colorWithRed:3/255.0 green:232/255.0 blue:80/255.0 alpha:1];
            btn.layer.borderColor =  btn.backgroundColor.CGColor;
        }
        
       else if (i == carfixString.length){
            btn.backgroundColor = kHexColor(0xc3c3c3);
            [resultString appendString:@" "];
        }else{
            [resultString appendString:@" "];
        }
        
        [btn setTitleColor:kHexColor(0x2d82d7) forState:(UIControlStateNormal)];
        btn.tag = BTNTAG + i;
        
        [btn addTarget:self action:@selector(clickBtn:) forControlEvents:(UIControlEventTouchUpInside)];
        [self addSubview:btn];
        lastX = btn.maxX - 1;
    }
    
    [self addSubview:tipsLabel];
    [self addSubview:cameraBtn];
    return self;
}

- (void)showKeyBoardView{
    UIButton *btn = [[UIButton alloc] init];
    
    NSString *carfixString = @"";
    
    NSMutableString *carNo = carfixString.mutableCopy;
    for (int i = (int)carfixString.length; i < 8; i++) {
        [carNo appendFormat:@" "];
    }
    
    [self setCarNo:carNo];
    
    btn.tag = BTNTAG + carfixString.length;
    [self clickBtn:btn];
}

- (void)clickBtn:(UIButton *)btn{
    
    // UIButton *oldBtn = [self viewWithTag:BTNTAG + _keyBoardView.index];
    // oldBtn.backgroundColor = kUIColorFromRGB(0xc3c3c3);
    int tag = (int)btn.tag - BTNTAG;
    
    
    if (![_keyBoardView  isDescendantOfView:[HSTool getWindow]]) {
        _keyBoardView = [[KeyBoardView alloc]initWithFrame:CGRectMake(0, kScreenH - (kScreenW/2.0) - 40 - 10 , kScreenW, kScreenW/2.0 + 10 + 40) defaultString:resultString];
        
        [[HSTool getWindow] addSubview:_keyBoardView];
    }
    
    [_keyBoardView reloadResultStringWithString:resultString];
    
    _keyBoardView.hidden = NO;
    _keyBoardView.maxLength = 8;
    _keyBoardView.index = tag;
    
    if (![_contentLabel isDescendantOfView:[HSTool getWindow]]) {
        // 点击键盘按钮后，提示View
        _contentLabel = [[UILabel alloc]initWithFrame:CGRectMake([[UIScreen mainScreen] bounds].size.width/2-35, 34+50+64, 70, 70)];
        _contentLabel.tag = 219;
        _contentLabel.textAlignment = NSTextAlignmentCenter;
        _contentLabel.textColor = [UIColor whiteColor];
        _contentLabel.backgroundColor = kHexColor(0x303030);
        _contentLabel.layer.cornerRadius = _contentLabel.frame.size.width/2.0;
        _contentLabel.layer.masksToBounds = YES;
        _contentLabel.font = [UIFont systemFontOfSize:40];
        _contentLabel.hidden = YES;
        [[HSTool getWindow] addSubview:_contentLabel];
    }
    
    kWeakSelf
    _keyBoardView.removeKeyBoardViewBlock = ^{
        if (weakSelf.removeSelfBlock) {
            weakSelf.removeSelfBlock();
        }
    };
    _keyBoardView.block = ^(NSString * result,NSString *changeString){
        
        resultString = [NSMutableString stringWithFormat:@"%@",result];
        //NSLog(@"输入结果:%@",result);
        
        [weakSelf setBtnTitles:result];
        
        if (changeString.length > 0) {
            
            weakSelf.contentLabel.alpha = 1;
            weakSelf.contentLabel.text = changeString;
            weakSelf.contentLabel.hidden = NO;
            
            [UIView animateWithDuration:1.5f animations:^{
                weakSelf.contentLabel.alpha = 0;
            } completion:^(BOOL finished) {
                weakSelf.contentLabel.hidden = YES;
            }];
        }
    };
    
    _keyBoardView.okBlock =  ^(NSString * result){
        result = [result stringByReplacingOccurrencesOfString:@" " withString:@""];
        if (_keyBoardView.effectiveNum == _keyBoardView.maxLength || _keyBoardView.effectiveNum == 7 || _keyBoardView.effectiveNum == 8) {
            [weakSelf.keyBoardView removeFromSuperview];
            [weakSelf.contentLabel removeFromSuperview];
            
            //   NSString *carfixString = ([[NSUserDefaults standardUserDefaults] objectForKey:CARFIX_KEY] ? : @"");
            
            resultString = [NSMutableString stringWithFormat:@"%@",result];
//            [weakSelf.carInputViewDelegate getCarNoInputResult:result];
            if (weakSelf.carInputViewDelegate) {
                [weakSelf.carInputViewDelegate getCarNoInputResult:result];
            }
            
            if (weakSelf.carNoInputBlock) {
                weakSelf.carNoInputBlock(result);
            }
            return ;
        }
        
    };
    
}

- (void)setBtnTitles:(NSString *)titles{
    
    for (int i = 0; i < _maxLength; i++) {
        NSString *title = @"";
        if (i < titles.length) {
            title = [titles substringWithRange:NSMakeRange(i, 1)];
        }
        
        UIButton *btn = [self viewWithTag:BTNTAG + i];
        [btn setTitle:title forState:(UIControlStateNormal)];
        btn.backgroundColor  = (i == _keyBoardView.index) ? kHexColor(0xc3c3c3) : [UIColor whiteColor];
        if (i == 7) {
            btn.backgroundColor = [UIColor colorWithRed:3/255.0 green:232/255.0 blue:80/255.0 alpha:1];
        }
    }
}

- (void)setCarNo:(NSString *)carNo{
    if (!(carNo.length == 7 || carNo.length == 8)) {
        return;
    }
    resultString = [[NSMutableString alloc] initWithFormat:@"%@",carNo];
    [self setBtnTitles:carNo];
    [_keyBoardView reloadResultStringWithString:carNo];
}


- (void)cameraBtn{
    
    [self removeKeyBoadView];
    
    PlateIDCameraViewController *vc = [[PlateIDCameraViewController alloc] init];
    
    kWeakSelf
    vc.carIdContent = ^(NSString *result){
        if (result.length != 7 && result.length != 8) {
            return ;
        }
        weakSelf.keyBoardView.index = 6;
        resultString = [NSMutableString stringWithFormat:@"%@",result];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"识别结果:%@",result);
            
            [weakSelf setBtnTitles:result];
            if (weakSelf.carInputViewDelegate) {
                [weakSelf.carInputViewDelegate getCarNoInputResult:result];
            }
            
            if (weakSelf.carNoInputBlock) {
                weakSelf.carNoInputBlock(result);
            }
        });
        
    };
//    [self.vc presentViewController:vc animated:YES completion:nil];
    vc.cancelBlock = ^{
        [weakSelf removeFromSuperview];
    };
    if ([self.vc.navigationController respondsToSelector:@selector(pushViewController:animated:)]) {
        [self.vc.navigationController pushViewController:vc animated:YES];
    }else{
        [self.vc presentViewController:vc animated:YES completion:nil];
    }
}

- (void)removeKeyBoadView{
    [self.keyBoardView removeFromSuperview];
    [self.contentLabel removeFromSuperview];
    
}

@end
